package com.h3c.nem.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eos.common.util.IdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.h3c.nem.client.AbilityClient;
import com.h3c.nem.dto.PageQueryDTO;
import com.h3c.nem.dto.TbOfferCompanyRelaDTO;
import com.h3c.nem.dto.beisen.PtEnumDTO;
import com.h3c.nem.dto.mapstruct.NewWorkerDTO;
import com.h3c.nem.entity.SdEmailTemplate;
import com.h3c.nem.entity.TbOfferWorker;
import com.h3c.nem.mapper.SdEmailTemplateMapper;
import com.h3c.nem.mapper.TbOfferCompanyRelaMapper;
import com.h3c.nem.entity.TbOfferCompanyRela;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ITbOfferCompanyRelaService;
import com.h3c.nem.utils.AppBusinessException;
import groovy.util.logging.Slf4j;
import org.apache.commons.collections4.ArrayStack;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 实现类
 *
 * @author chenyifan
 * @since 2022-06-14 16:39:02
 */
@Slf4j
@Service
public class TbOfferCompanyRelaServiceImpl extends ServiceImpl<TbOfferCompanyRelaMapper, TbOfferCompanyRela> implements ITbOfferCompanyRelaService {

    @Autowired
    AbilityClient abilityClient;

    @Value("${ptability.token}")
    private String ptToken;

    @Resource
    private SdEmailTemplateMapper sdEmailTemplateMapper;

    @Resource
    private TbOfferCompanyRelaMapper tbOfferCompanyRelaMapper;

    @Resource
    private SdEmailTemplateServiceImpl sdEmailTemplateService;

    /**
     * @Description: 获取人事范围和Offer模板对应关系
     * @Param: pageQuery 分页参数
     * @Author: h24002
     * @Date: 2022/6/22
     */
    @Override
    public PageInfo<TbOfferCompanyRelaDTO> getFuzzyListForPage(PageQueryDTO pageQuery) {
        // 构造分页参数
        Page page = PageHelper.startPage(pageQuery.getPageNum(), pageQuery.getPageSize());
        //查询数据
        List<TbOfferCompanyRela> list = tbOfferCompanyRelaMapper.selectList(null);
        List<TbOfferCompanyRelaDTO> dtoList = JSONObject.parseArray(JSONObject.toJSONString(list),TbOfferCompanyRelaDTO.class);
        if (dtoList.size() > 0) {
            Map<String, String> offerTempMap = getOfferTemplateCodeNameMap();
            Map<String, String> companyMap = getCompanyCodeNameMap();

            for (TbOfferCompanyRelaDTO tbOfferCompanyRelaDTO : dtoList) {
                String templateId = tbOfferCompanyRelaDTO.getTemplateId();
                tbOfferCompanyRelaDTO.setTemplateName(offerTempMap.get(templateId));

                String companyCode = tbOfferCompanyRelaDTO.getCompanyCode();
                tbOfferCompanyRelaDTO.setCompanyName(companyMap.get(companyCode));
            }
        }

        PageInfo<TbOfferCompanyRelaDTO> pageInfo = page.toPageInfo();
        pageInfo.setList(dtoList);
        return pageInfo;
    }


    /**
     * @Description: 键值码对应的枚举数组
     * @Param: enumCode  键值编码
     * @Author: huangweizhen
     * @Date: 2022/6/21
     */
    public List<PtEnumDTO> getEnumList(String enumCode) {
        PtEnumDTO enumDTO = new PtEnumDTO();
        enumDTO.setAppId("nem-manager");
        enumDTO.setEnumCode(enumCode);
        JSONObject ptEnumRes = abilityClient.getPtEnum(enumDTO, ptToken);
        return JSONObject.parseArray(JSONObject.toJSONString(ptEnumRes.get("data")), PtEnumDTO.class);
    }

    /**
     *@Description: 获取模板的集合
     *@Param: emailTemplateType  模板类型：1 沟通函模板；99 Offer模板
     *@Author: huangweizhen
     *@Date: 2022/6/22
     */
    @Override
    public List<SdEmailTemplate> getTemplateCodeNameList(Integer emailTemplateType)
    {
        LambdaQueryWrapper<SdEmailTemplate> emailTemplateQueryWrapper = new LambdaQueryWrapper<>();
        emailTemplateQueryWrapper.select(SdEmailTemplate::getEmailTemplateId,SdEmailTemplate::getEmailTemplateName)
                .eq(SdEmailTemplate::getEmailTemplateType,emailTemplateType);
        List<SdEmailTemplate> sdEmailTemplates = sdEmailTemplateMapper.selectList(emailTemplateQueryWrapper);
        return sdEmailTemplates;
    }

    /**
     * @Description: 获取Offer模板集合
     * @Author: huangweizhen
     * @Date: 2022/6/23
     */
    private Map<String, String> getOfferTemplateCodeNameMap() {
        //获取到offer模板列表
        List<SdEmailTemplate> offerTempList = getTemplateCodeNameList(99);
        return offerTempList.stream().collect(Collectors.toMap(SdEmailTemplate::getEmailTemplateId, SdEmailTemplate::getEmailTemplateName));
    }

    /**
     * @Description: 获取人事范围集合
     * @Author: huangweizhen
     * @Date: 2022/6/23
     */
    private Map<String, String> getCompanyCodeNameMap() {
        //获取到人事范围列表
        List<PtEnumDTO> companyData = getEnumList("NEW_STAFF_PERSONALRANGENAME");
        return companyData.stream().collect(Collectors.toMap(PtEnumDTO::getValue, PtEnumDTO::getNameZh));
    }

    /**
     * @Description: 插入或更新人事范围和Offer模板对应关系
     * @Param: info 对应关系模型数据
     * @Author: huangweizhen
     * @Date: 2022/6/23
     */
    @Override
    public boolean saveInfo(TbOfferCompanyRela info) {
        if (!StringUtils.hasText(info.getCompanyCode())) {
            throw new AppBusinessException("人事范围编码不可为空");
        }
        if (!StringUtils.hasText(info.getTemplateId())) {
            throw new AppBusinessException("Offer模板ID不可为空");
        }
        if (!StringUtils.hasText(info.getCompanyName())) {
            info.setCompanyName("未知人事范围名称");
        }
        //根据对应关系ID判断是否新增或更新
        String relaId = info.getRelaId();
        if (StringUtils.hasText(relaId)) {
            //走更新数据
            TbOfferCompanyRela model = tbOfferCompanyRelaMapper.selectById(relaId);
            if (model == null) {
                throw new AppBusinessException("未找到对应关系信息，请刷新后重试");
            }
            return this.updateById(info);
        } else {
            //走插入数据
            info.setRelaId(String.valueOf(IdWorker.nextId()));
            return this.save(info);
        }
    }

    /**
     * @Description: 删除人事范围和Offer模板对应关系
     * @Param: relaId 对应关系ID
     * @Author: huangweizhen
     * @Date: 2022/6/23
     */
    @Override
    public boolean delInfo(String relaId) {
        if (!StringUtils.hasText(relaId)) {
            throw new AppBusinessException("对应关系ID不可为空");
        }

        return this.removeById(relaId);
    }

    /**
     * @Description: 查询单个人事范围和Offer模板对应关系
     * @Param: relaId 对应关系ID
     * @Author: huangweizhen
     * @Date: 2022/6/23
     */
    @Override
    public TbOfferCompanyRelaDTO selectOnlyInfo(String relaId) {
        if (!StringUtils.hasText(relaId)) {
            throw new AppBusinessException("对应关系ID不可为空");
        }

        TbOfferCompanyRela info = tbOfferCompanyRelaMapper.selectById(relaId);
        if (info != null) {
            TbOfferCompanyRelaDTO model = JSONObject.parseObject(JSONObject.toJSONString(info), TbOfferCompanyRelaDTO.class);
            if (StringUtils.hasText(model.getCompanyCode())) {
                Map<String, String> companyMap = getCompanyCodeNameMap();
                String companyCode = model.getCompanyCode();
                model.setCompanyName(companyMap.get(companyCode));
            }
            if (StringUtils.hasText(model.getTemplateId())) {
                Map<String, String> offerTempMap = getOfferTemplateCodeNameMap();
                String templateId = model.getTemplateId();
                model.setTemplateName(offerTempMap.get(templateId));
            }
            return model;
        }
        return null;
    }

}

